package vn.com.epi.servlet;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/delete-file.html")
public class DeleteFileServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    public DeleteFileServlet() {
        super();
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/jsp/delete-file-form.jsp").forward(request, response);
    }

    
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String path = request.getParameter("path");
        String respond = "";
        try {
            File file = new File(path);
            if(file.delete()){
                respond = file.getName() + " is deleted";
            }else{
                respond = "Delete operation is failed.";
            }
        } catch (Exception e) {
            respond = "File permission problems. Can't delete this file";
        } finally {
            request.setAttribute("respond", respond);
            request.getRequestDispatcher("/WEB-INF/jsp/respond.jsp").forward(request, response);
        }
    }
}
